package com.fingard.dsp.bank.directbank.hsbc02;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBalance;
import com.fingard.dsp.bank.reqrespobj.balance.Req7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.Req7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsBalDetail;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsHisBalDetail;
import com.fingard.text.StringHelper;
import sun.misc.BASE64Decoder;

import java.math.BigDecimal;
import java.util.Calendar;

/**
 * 汇丰银行api余额查询
 * @date 2020-04-26
 */
public class HSBC02Balance extends HSBC02Base implements IBalance {

    /**
     * 汇丰银行当前余额查询
     * @param p_req7506
     * @return
     * @throws Exception
     */
    @Override
    public RetAts7506BalQry d_7506_BalQry(Req7506BalQry p_req7506) throws Exception {
        RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
        retAts.writeStart();
        JSONArray jsonArrayReq=new JSONArray();
        while(p_req7506.readRecord()) {
            JSONObject banlanceReqJson = new JSONObject();
            banlanceReqJson.put("accountNumber", p_req7506.readedDetail.actNum);//Account Number. Max length 34
            banlanceReqJson.put("accountCountry",
                    getBankConfig().getMapValueByKey("balanceAndConturyMapping",p_req7506.readedDetail.actNum));
            banlanceReqJson.put("institutionCode", "HBAP");//Institution Code i.e HBEU
            banlanceReqJson.put("accountType", "CA");//Account Type i.e CA Ye
            jsonArrayReq.add(banlanceReqJson);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("accountBalances", jsonArrayReq);
        //发送请求报文
        String[] bankResult = sendToBank(jsonObject.toJSONString(),p_req7506.reqHeader.transType,p_req7506.reqHeader.commandCode,"balancesRequestBase64");
        if(bankResult[0].length()==0){
            JSONObject balanceBodyJson = JSONObject.parseObject(bankResult[1]);
            if(balanceBodyJson!=null && balanceBodyJson.get("balances")!=null){
                JSONArray acctInfo = JSON.parseArray(balanceBodyJson.getString("balances"));
                if(acctInfo!=null && acctInfo.size()>0){
                    for (int i = 0; i < acctInfo.size(); i++){
                        JSONObject content=acctInfo.getJSONObject(i);
                        RetAtsBalDetail detail = new RetAtsBalDetail();
                        detail.respCode = "0";//响应码
                        detail.respInfo = "成功";//响应信息
                        detail.actNum = content.getString("identification").substring(8);//账号
                        String openAvaiBalance="";
                        String openBookBalance="";
                        String interimAvaiBalance="";
                        String interimBookBalance="";
                        String cur="";
                        JSONArray balList=JSON.parseArray(content.getString("balance"));
                        if(balList==null || balList.size()==0){
                            retAts.writeRespCode("-1");
                            retAts.writeRespInfo("Data is empty.");
                            break;
                        }
                        for(int j = 0; j < balList.size(); j++){
                            JSONObject bal=balList.getJSONObject(j);
                            String type=bal.getString("type");
                            String creditDebitIndicator=bal.getString("creditDebitIndicator");
                            JSONObject amountJson=bal.getJSONObject("amount");
                            String amount=amountJson.getString("amount");
                            if("Debit".equals(creditDebitIndicator)){
                                if(amount.startsWith("-")){
                                    amount=amount.substring(1);
                                }else {
                                    amount="-"+amount;
                                }
                            }
                            cur=amountJson.getString("currency");
                            if("OPAV".equals(type)){
                                openAvaiBalance=amount;
                            }
                            if("OPBD".equals(type)){
                                openBookBalance=amount;
                            }
                            if("ITAV".equals(type)){
                                interimAvaiBalance=amount;
                            }
                            if("ITBD".equals(type)){
                                interimBookBalance=amount;
                            }
                        }
                        //币种
                        detail.actCur = convertCurToATS(cur);
                        //可用余额
                        if(StringHelper.hasAnyChar(interimAvaiBalance)){
                            detail.availBal = interimAvaiBalance;
                        }else if(StringHelper.hasAnyChar(openAvaiBalance)){
                            detail.availBal = openAvaiBalance;
                        }
                        //当前余额
                        if(StringHelper.hasAnyChar(interimBookBalance)){
                            detail.currBal = interimBookBalance;
                        }else if(StringHelper.hasAnyChar(openBookBalance)){
                            detail.currBal = openBookBalance;
                        }
                        if(StringHelper.isNullOrEmpty(detail.availBal) && StringHelper.isNullOrEmpty(detail.currBal)){
                            detail = new RetAtsBalDetail();
                            detail.respCode="-1";
                            detail.respInfo="账号"+detail.actNum+"查询余额异常，银行返回的余额为空";
                        }
                        retAts.writeRetDetail(detail,p_req7506.isBatch);
                    }
                }else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo("Data is empty.");
                }
            }else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo("Data is empty.");
            }
        }else {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(bankResult[1]);
        }
        retAts.writeEnd();
        return retAts;
    }

    /**
     * 汇丰银行历史余额查询
     * @param p_req7505
     * @return
     * @throws Exception
     */
    @Override
    public RetAts7505HisBalQry d_7505_BalQry(Req7505HisBalQry p_req7505) throws Exception {
        RetAts7505HisBalQry retAts = new RetAts7505HisBalQry(p_req7505.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        //起始日期
        Calendar tmpCalendarFrom = Calendar.getInstance();
        tmpCalendarFrom.setTime(p_req7505.getDateFrom());
        //结束日期
        Calendar tmpCalendarTo = Calendar.getInstance();
        tmpCalendarTo.setTime(p_req7505.getDateTo());
        int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
        int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
        //按天循环查询
        while(tmpIntFrom<=tmpIntTo) {
            //获取起始时间
            int intFromStep = tmpIntFrom;
            //起始时间+1
            tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
            //重新设置起始时间
            tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            //查询明细数据
            String qryDate=Format.Date10Format.format(Format.Date8Format.parse(intFromStep+""));
            String[] decryptRsp=qryTransactionJson(p_req7505.actNum,qryDate);
            //处理响应，获取余额
            if(decryptRsp[0].length()==0){
                JSONObject balanceBodyJson=JSONObject.parseObject(decryptRsp[1]);
                if(balanceBodyJson==null) {
                    WriteBankLogLn(qryDate+" No transactions found");
                    continue;
                }
                JSONObject transactionsJson=balanceBodyJson.getJSONObject("transactions");
                if(transactionsJson==null) {
                    WriteBankLogLn(qryDate+" No transactions found");
                    continue;
                }
                String actNum=transactionsJson.getString("requestorAccountId");
                if(!actNum.equals(p_req7505.actNum)){
                    WriteBankLogLn("账号校验异常");
                    continue;
                }
                JSONArray balanceArray=transactionsJson.getJSONArray("balance");
                if(balanceArray==null || balanceArray.size()==0) {
                    WriteBankLogLn(qryDate+" No transactions found");
                    continue;
                }
                //处理数据
                RetAtsHisBalDetail detail = new RetAtsHisBalDetail();
                String openAvaiBalance="";
                String openBookBalance="";
                String interimAvaiBalance="";
                String interimBookBalance="";
                for(int i=0;i<balanceArray.size();i++){
                    JSONObject balanceJson=balanceArray.getJSONObject(i);
                    String type=balanceJson.getString("type");
                    String creditDebitIndicator=balanceJson.getString("creditDebitIndicator");
                    JSONObject amountJson=balanceJson.getJSONObject("amount");
                    String amount=amountJson.getString("amount");
                    if("Debit".equals(creditDebitIndicator)){
                        if(amount.startsWith("-")){
                            amount=amount.substring(1);
                        }else {
                            amount="-"+amount;
                        }
                    }
                    if("OPAV".equals(type)){
                        openAvaiBalance=amount;
                    }
                    if("OPBD".equals(type)){
                        openBookBalance=amount;
                    }
                    if("ITAV".equals(type)){
                        interimAvaiBalance=amount;
                    }
                    if("ITBD".equals(type)){
                        interimBookBalance=amount;
                    }
                }
                //可用余额
                if(StringHelper.hasAnyChar(interimAvaiBalance)){
                    detail.availBal = interimAvaiBalance;
                }else if(StringHelper.hasAnyChar(openAvaiBalance)){
                    detail.availBal = openAvaiBalance;
                }
                //当前余额
                if(StringHelper.hasAnyChar(interimBookBalance)){
                    detail.actBal = interimBookBalance;
                }else if(StringHelper.hasAnyChar(openBookBalance)){
                    detail.actBal = openBookBalance;
                }
                //时间
                detail.balDate=Format.Date10Format.format(Format.Date8Format.parse(intFromStep+""));
                retAts.writeRetDetail(detail);
            }else if(decryptRsp[0].equals("RJCT") && decryptRsp[1].contains("No transactions found")){
                //查不到明细不做处理，继续查下个日期的余额
                WriteBankLogLn(qryDate+" No transactions found");
            }else {
                tmpRespCode = "-1";
                tmpRespInfo = decryptRsp[1];
                break;
            }
        }
        if (tmpRespCode.equals("-1")) {
            retAts = new RetAts7505HisBalQry(p_req7505.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("返回结果为空，所查询时间段内不存在历史余额");
        }
        retAts.writeEnd();
        return retAts;
    }
}
